package com.lin.sms.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lin.sms.dao.IUserDAO;
import com.lin.sms.domain.User;
import com.lin.sms.util.Constant;
import com.lin.sms.util.Utils;

@Controller
public class UserController {
    @Autowired
    IUserDAO userDao;

    @RequestMapping("/login")
    public ModelAndView login() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/login.jsp");
        return mv;
    }

    @RequestMapping("/checkLogin")
    public ModelAndView checkLogin(String username, String password, String checkCode, HttpServletRequest req)
        throws Exception {
        // 新建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        if (req == null || checkCode == null) {
            mv.setViewName("/login.jsp");
            return mv;
        }
        // 验证验证码是否空
        String sessionRandomCode = (String)req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
       // System.out.println(sessionRandomCode);
        if (checkCode == null || sessionRandomCode == null) {
            mv.addObject("errorMsg", "验证码不可空");
            mv.setViewName("login.jsp");
            return mv;
        }
        // 验证验证码是否正确
        if (!checkCode.equalsIgnoreCase(sessionRandomCode)) {
            mv.addObject("errorMsg", "验证码错误");
            mv.setViewName("/login.jsp");
            return mv;
        }

        // 将用户输入的密码加密
        password = Utils.passwordTransform(password);
        // 根据username和password从数据库中拿user对象
        User user = userDao.checkLogin(username, password);
        // 如果user为空,返回登录页面
        if (user == null) {
            mv.addObject("errorMsg", "用户名或密码错误");
            mv.setViewName("/login.jsp");
            return mv;
        }

        // 将user存入Session
        req.getSession().setAttribute(Constant.USER_IN_SESSION, user);
        // 如果以上都通过,则跳转至welcome界面
        mv.setViewName("/scores/welcome");
        return mv;
    }
    
    
    @RequestMapping("/exit")
    public String exit(HttpServletRequest req) {
        //移除USER_IN_SESSION
        req.getSession().removeAttribute(Constant.USER_IN_SESSION);
        return "redirect:/login.jsp";
    }
}
